//再mainlayout使用
import { useEffect, useState } from "react";
import { GetUserInfo } from "../service";
import useGetUserInfo_redux from "./useGetUserInfo_redux";
import { useRequest } from "ahooks";
import { useDispatch } from "react-redux";
import { setUserInfo_reducer } from "../store/userInfo";
import { getUserToken } from "../until/userToken";

function useGetUserDate() {
  const dispatch = useDispatch();
  const [waittingData, setwaittingData] = useState(true);
  //ajax加载完用户信息后直接放在redux中  无需再返回
  //如果已经获取了就没有必要再获取一边
  const { username } = useGetUserInfo_redux();
  const { run } = useRequest(GetUserInfo, {
    manual: true,
    onSuccess(res) {
      // 存储到redux
      dispatch(setUserInfo_reducer(res as any));
    },
    onFinally() {
      setwaittingData(false);
    },
  });
  useEffect(() => {
    if (username) {
      setwaittingData(false);
      return;
    }
    //使用ajax加载用户信息
    //如果redux中没有用户信息则获取网络的用户信息
    if (getUserToken()) {
      run();
    } else {
      setwaittingData(false);
    }
  }, [username]);
  // console.log("waittingDatawaittingDatawaittingData", waittingData);
  return { waittingData };
}

export default useGetUserDate;
